<template>
  <div class="series-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" ref="searchForm" class="search-form">
        <el-form-item label="系列名称" prop="name">
          <el-input v-model="searchForm.name" placeholder="请输入系列名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="所属品牌" prop="brandId">
          <el-select v-model="searchForm.brandId" placeholder="请选择所属品牌" clearable>
            <el-option v-for="item in brandOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div class="table-header">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增系列</el-button>
      </div>
      
      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="name" label="系列名称" min-width="120"></el-table-column>
        <el-table-column prop="brandName" label="所属品牌" width="150"></el-table-column>
        <el-table-column label="系列LOGO" width="150" align="center">
          <template slot-scope="scope">
            <el-image 
              v-if="scope.row.image"
              style="width: 100px; height: 40px"
              :src="scope.row.image"
              :preview-src-list="[scope.row.image]">
            </el-image>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="100" align="center"></el-table-column>
        <el-table-column label="是否显示" width="100" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.showStatus"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageParams.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="resetForm('form')">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="系列名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入系列名称"></el-input>
        </el-form-item>
        <el-form-item label="所属品牌" prop="brandId">
          <el-select v-model="form.brandId" placeholder="请选择所属品牌">
            <el-option v-for="item in brandOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" placeholder="请输入排序"></el-input-number>
        </el-form-item>
        <el-form-item label="是否显示" prop="showStatus">
          <el-switch
            v-model="form.showStatus"
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
          ></el-switch>
        </el-form-item>
        <el-form-item label="系列LOGO" prop="image">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="customUpload"
            :show-file-list="false"
            :before-upload="beforeLogoUpload"
          >
            <img v-if="form.image" :src="form.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'VehicleSeries',
  data() {
    return {
      // 搜索表单
      searchForm: {
        name: '',
        brandId: ''
      },
      // 分页参数
      pageParams: {
        current: 1,
        size: 10
      },
      // 表格数据
      tableData: [],
      total: 0,
      loading: false,
      // 品牌选项
      brandOptions: [],
      // 对话框
      dialogVisible: false,
      dialogTitle: '新增系列',
      // 表单数据
      form: {
        id: null,
        name: '',
        brandId: '',
        sort: 0,
        showStatus: 1,
        image: ''
      },
      // 表单校验规则
      rules: {
        name: [{ required: true, message: '请输入系列名称', trigger: 'blur' }],
        brandId: [{ required: true, message: '请选择所属品牌', trigger: 'change' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.fetchData()
    this.fetchBrands()
  },
  methods: {
    // 获取系列列表数据
    fetchData() {
      this.loading = true
      const params = {
        current: this.pageParams.current,
        size: this.pageParams.size,
        ...this.searchForm
      }
      
      request({
        url: '/car-vehicle/vehicle-series/page',
        method: 'get',
        params
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 获取品牌列表
    fetchBrands() {
      request({
        url: '/car-vehicle/vehicle-brands/list/available',
        method: 'get'
      }).then(res => {
        this.brandOptions = res.data
      })
    },
    // 处理搜索
    handleSearch() {
      this.pageParams.current = 1
      this.fetchData()
    },
    // 重置搜索
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.handleSearch()
    },
    // 处理页码变更
    handleCurrentChange(current) {
      this.pageParams.current = current
      this.fetchData()
    },
    // 处理每页数量变更
    handleSizeChange(size) {
      this.pageParams.size = size
      this.pageParams.current = 1
      this.fetchData()
    },
    // 处理新增
    handleAdd() {
      this.dialogTitle = '新增系列'
      this.form = {
        id: null,
        name: '',
        brandId: '',
        sort: 0,
        showStatus: 1,
        image: ''
      }
      this.dialogVisible = true
    },
    // 处理编辑
    handleEdit(row) {
      this.dialogTitle = '编辑系列'
      this.form = { ...row }
      this.dialogVisible = true
    },
    // 处理删除
    handleDelete(row) {
      this.$confirm('确认删除该系列?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: `/car-vehicle/vehicle-series/${row.id}`,
          method: 'delete'
        }).then(() => {
          this.$message.success('删除成功')
          this.fetchData()
        })
      }).catch(() => {})
    },
    // 处理状态变更
    handleStatusChange(row) {
      request({
        url: `/car-vehicle/vehicle-series/${row.id}/status/${row.showStatus}`,
        method: 'put'
      }).then(() => {
        this.$message.success('状态修改成功')
      })
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          request({
            url: '/car-vehicle/vehicle-series/save',
            method: 'post',
            data: this.form
          }).then(() => {
            this.$message.success(`${this.form.id ? '更新' : '添加'}成功`)
            this.dialogVisible = false
            this.fetchData()
          })
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // LOGO上传前处理
    beforeLogoUpload(file) {
      const isImage = file.type.indexOf('image/') === 0
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    // 自定义上传处理
    customUpload(event) {
      const file = event.file
      const formData = new FormData()
      formData.append('file', file)

      request({
        url: '/car-integration/files/upload',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        console.log('上传响应数据:', res);
        if (res.code === 200) {
          this.form.image = res.data.url;
          console.log('设置logo URL:', this.form.image);
          this.$forceUpdate();
          this.$message.success('上传成功');
        } else {
          this.$message.error('上传失败：' + res.message);
        }
      }).catch(err => {
        console.error('上传错误:', err);
        this.$message.error('上传失败')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.series-container {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .table-header {
      margin-bottom: 20px;
      display: flex;
      justify-content: flex-start;
    }
  }
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
  
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 60px;
    
    &:hover {
      border-color: #409EFF;
    }
    
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 60px;
      line-height: 60px;
      text-align: center;
    }
    
    .avatar {
      width: 178px;
      height: 60px;
      display: block;
      object-fit: contain;
    }
  }
}
</style> 